#include <iostream>
#include <stdio.h>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;

int main(int argc, char** argv)
{
    char filename[1024];
    string line;
    int i, j;
    double sTime, nTime, time;
    ifstream file;
    ofstream out, outfile;

    if (argc < 3)
    {
	cout << "Usage: maketimes prefix maxk" << endl;
	return 0;
    }

    out.open("temp.txt");
    for(i = 2; i < atoi(argv[2]); ++i)
    {
	nTime = 0.0;
	sprintf(filename, "%sNAIVE-1-TIME.txt", argv[1]);
	file.open(filename);
	if (file.is_open())
	{
	    while (getline(file, line))
	    {
		sscanf(line.c_str(), "%lf", &time);
		nTime += time;
	    }
	    file.close();
	}
	    
	sTime = 0.0;
        sprintf(filename, "%s%dBINS-1-TIME.txt", argv[1], i);
        file.open(filename);
        if (file.is_open())
        {
            while (getline(file, line))
            {
                sscanf(line.c_str(), "%lf", &time);
                sTime += time;
            }
            file.close();
        }

	// extract the graph name by truncating the string
	//j = 0;
	//while (argv[i][j] != '-') { j++; }
	//argv[i][j] = '\0';
	
	out << i << "\t" << nTime << "\t" << sTime << "\t" << nTime/sTime << endl;
    }
    out.close();

    outfile.open("plot.p");
    outfile << "set term postscript eps color\n";
    outfile << "set output \"" << argv[1] << "varyk-TIME.eps\"\n";
    outfile << "set xlabel 'k'\n";
    outfile << "set ylabel 'running time (seconds)'\n";
    outfile << "set logscale y\n";
    outfile << "set key left top\n";
    outfile << "set key box\n";
    outfile << "set size .75,.75\n";
    outfile << "set style line 1 lw 3 lc rgb \"red\"\n";
    outfile << "set style line 2 lc rgb \"blue\" lw 2\n";

    outfile << "plot \"temp.txt\" using 1:3 title 'k-bins' ls 1 with linespoints, \"temp.txt\" using 1:2 title 'Naive' ls 2 with linespoints" << endl;
	
    outfile.close();

    if (system("gnuplot plot.p"))
        cout << "Error with plotting.\n";
    char command[1024];

    sprintf(command, "convert -density 500 %svaryk-TIME.eps %svaryk-TIME.pdf", argv[1], argv[1]);

    if (system(command))
        cout << "Error converting to pdf.\n";


    
    return 0;
}
